// router/index.js
import { createRouter, createWebHashHistory, Router } from "vue-router";
import store from "@/store";
import { useUserMemberStore } from "/stores/usermember";
const routes = [
  // ...其他路由配置
  {
    path: "/pages/index/index",
    component: () => import("@/pages/index/index.vue"),
    meta: {
      requiresAuth: true, // 标记该路由需要登录
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});


router.beforeEach(async (to, from, next) => {
  const member = useUserMemberStore();
  const isAuthenticated = member.token !== "";

  if (to.meta.requiresAuth && isAuthenticated) {
    try {
      // 发起验证token有效的API请求
	  // 返回的数据
	  // {"success":false,"message":"Token失效，请重新登录!","code":401,"result":null,"timestamp":1713676453191}
      const {code} = await uni.request({
        url: "http://129.204.87.250:8080/jeecg-boot/moyunOrderInformation/moyunOrderInformation/selectAllOrder",
        method: "GET",
        header: {
          "X-Access-Token": member.token,
        },
      });

      if (code==401){
        // 如果服务器返回token失效，重定向至登录页
        next("/pages/login/login");
      }else{
		  
		  // 如果服务器返回token有效，允许访问
		  next();
	  }
    } catch (error) {
      // 如果请求失败（如网络问题、服务器错误等），出于安全考虑，也可以重定向至登录页
      next("/pages/login/login");
    }
  } else {
    // 用户未登录或访问的页面无需登录，允许访问
    next();
  }
});

export default router;